package io.github.lee.app.unsplash.ui.main.home.page

import android.app.Application
import com.chad.library.adapter.base.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.app.unsplash.repository.TopicRepository
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.repository.domain.Topic
import io.github.lee.core.vm.BaseRefreshViewModel
import kotlinx.coroutines.delay
import javax.inject.Inject

@HiltViewModel
class TopicPhotoListVM @Inject constructor(
    application: Application,
    private val repo: TopicRepository
) : BaseRefreshViewModel<Photo>(application) {
    var topic: Topic? = null

    override fun onCreateAdapter(): BaseQuickAdapter<Photo, *> =
        TopicPhotoAdapter()

    //===Desc:===============================================================================

    private var page = 1
    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        if (isRefresh) {
            page = 1
        } else {
            page++
        }
        launchResult({
            //delay(10 * 1000L)
            repo.topicPhotoList(topic?.id ?: "", page, 10)
        }, {
            if (isRefresh) {
                error()
            } else {
                loadMoreFail()
            }
            page--
        }) {
            if (!it.isSuccess()) {
                if (isRefresh) {
                    error()
                } else {
                    loadMoreFail()
                }
                page--
                return@launchResult
            }
            val data = it.data
            if (data.isNullOrEmpty()) {
                if (isRefresh) {
                    empty()
                } else {
                    loadMoreSuccess(false)
                }
                page--
                return@launchResult
            }
            if (isRefresh) {
                submitList(data)
                refreshSuccess()
            } else {
                addAll(data)
                loadMoreSuccess(true)
            }
        }


    }


}